import {
  Text,
  Image,
  StyleSheet,
  TouchableOpacity,
  View,
  Dimensions,
  Animated,
  ScrollView,
  ScaleYTransform, TextInput, FlatList, Button, NativeModules,
} from "react-native";
import React, { useEffect, useRef, useState } from "react";
import AntDesign from "react-native-vector-icons/AntDesign";
import { useNavigation } from '@react-navigation/native';
import SongList from "../ListDetail/SongList";
import ListItem from "../ListDetail/ListItem";
import Colors from "../../util/Colors";
import Toast from "react-native-easy-toast";
import { get163PlayMusic } from "../../request/neteaseRequest";
import _ from 'lodash';
import { getQPlayMusic } from "../../request/QQRequest";
import { getMgPlayMusic } from "../../request/miguRequest";
import { getKgPlayMusic } from "../../request/kugouRequest";
import { getKwPlayMusic } from "../../request/kuwoRequest";
import FontAwesome from "react-native-vector-icons/FontAwesome";
export default function(props){

  const navigation = useNavigation();
  const [showList,setShowList] = useState(false);

  const [imgX,setImgX] = useState(0);
  const [textX,setTextX] = useState(0);
  const [textWidth,setTextWidth] = useState(0);
  const [moveIX,setMoveIX] = useState(0);
  const [moveTX,setMoveTX] = useState(0);
// fadeAnim will be used as the value for opacity. Initial Value: 0
  const scrollAnim = useRef(new Animated.Value(height*0.6+55)).current;


  let musicList=props.musicList;
  let currentMusic = props.currentMusic;
  useEffect(() => {
    if(props.toAdd){
      NativeModules.ToolModule.getPlayList().then((r) => {
        //console.log(r);
        let result = r.playList;
        setPlayList(JSON.parse(result));
      })
    }
    if(!currentMusic.init){
      //console.log('init current');
      initMusic(-1);
    }
    let wholeWidth = textWidth + 55;
    let start = (width - wholeWidth) / 2;
    let imx = start - imgX;
    let tmx = start + 55 - textX;

    setMoveIX(imx);
    setMoveTX(tmx);
  },[currentMusic,textX,imgX,textWidth,props.toAdd])


  let [playList,setPlayList] = useState([])
  function renderAddPlayList() {
    //console.log('toadd');
    //console.log(props.toAdd);
    return(
      <>
      {props.toAdd &&
          <View style={styles.addContain}>
            <View style={{width:width*0.8,marginTop:5}}>
              <Button title={'添加到播放列表'} color={Colors.colorPrimary} onPress={()=>{
                props.addPlayList(props.toAddValue);
                props.setToAdd(false);
              }}/>
            </View>
            <View style={{width:width*0.8,marginTop:5}}>
              <Text style={{fontSize:18}}>或添加到歌单：</Text>
            </View>
            <FlatList data={playList} renderItem={renderList}/>
            <View style={{width:width*0.8}}>
            <Button title={'取消'} color={Colors.colorLight} onPress={() => props.setToAdd(false)}/>
            </View>

          </View>

      }
      </>
    )
  }
  async function pressItem(item){
    //console.log("去存储次歌单")
    //console.log(item);
    let origin = null;
    await NativeModules.ToolModule.getListSongs(item.id).then((r) => {
      origin = r.songs;
    })
    let newSongs = [];
    if(origin === null || !origin){

    }else {
      newSongs = JSON.parse(origin);
    }
    if(props.toAddValue instanceof Array){
      //console.log("添加歌单到歌单");
      newSongs = _.concat(newSongs,props.toAddValue);
    }else {
      //console.log('添加单曲到歌单');
      newSongs.push(props.toAddValue);
    }
    //console.log('新歌单');
    //console.log(newSongs);
    await NativeModules.ToolModule.addListSong(item.id,JSON.stringify(newSongs)).then((r) => {
      //console.log(r);
    })
    props.setToAdd(false);
  }
  function renderList({item}){
    return(
      <TouchableOpacity onPress={() => pressItem(item)}>
          <Text style={styles.addInput}>{item.name}</Text>
      </TouchableOpacity>
    )

  }
  const toast = useRef(null);
  function handleVIP(){
    //console.log('vip~~~~~~~~~~~~');
    // scrollUp();
    toast.current.show('此歌曲需要登录或VIP');
  }
  const initMusic =  async (index) => {
    let data;
    if(index === -1){

      index = musicList.findIndex((r) => {
        return r.id === currentMusic.id && r.name === currentMusic.name;
      })
      data = props.currentMusic;
    }else {
      data = props.musicList[index];
    }
    let flag = true;
    if(data.from === '163'){
      //console.log(data);
      await get163PlayMusic(data.id,(r) => {
        let pre = musicList;
        if(r === -1){
          handleVIP();
          flag = false;
          currentMusic.resource = "";
          currentMusic.init = true;
          pre[index] = {
            ...pre[index],
            ...currentMusic
          }
        }else {
          if(!r.resource || r.resource === ''){
            handleVIP();
          }
          pre[index] = {
            ...pre[index],
            ...r
          }
          pre[index].init = true;
        }
        props.setMusicList(_.uniqBy(pre, 'id'));
        props.setCurrentMusic(pre[index]);
      })
    }else if(data.from === 'qq'){
      await getQPlayMusic(data.id,data.albumId,(r) => {
        let pre = musicList;
        if(r.resource === ''){
          handleVIP();
          flag = false;
          currentMusic.resource = "";
          currentMusic.init = true;
          pre[index] = {
            ...pre[index],
            ...currentMusic,
            ...r
          }
        }else {
          if(!r.resource || r.resource === ''){
            handleVIP();
          }
          pre[index] = {
            ...pre[index],
            ...r
          }
          //console.log(pre[index]);
          pre[index].init = true;
        }
        props.setMusicList(_.uniqBy(pre, 'id'));
        props.setCurrentMusic(pre[index]);
      })
    }else if(data.from === 'kugou'){
      await getKgPlayMusic(data.id,(r) => {
        let pre = musicList;
        if(r === -1){
          handleVIP();
          flag = false;
          currentMusic.resource = "";
          currentMusic.init = true;
          pre[index] = {
            ...pre[index],
            ...currentMusic
          }
        }else {
          if(!r.resource || r.resource === ''){
            handleVIP();
          }
          pre[index] = {
            ...pre[index],
            ...r
          }
          pre[index].init = true;
        }
        props.setMusicList(_.uniqBy(pre, 'id'));
        props.setCurrentMusic(pre[index]);

      })
    }else if(data.from === 'kuwo'){
      await getKwPlayMusic(data.id,(r) => {
        let pre = musicList;
        if(r === -1){
          handleVIP();
          flag = false;
          currentMusic.resource = "";
          currentMusic.init = true;
          pre[index] = {
            ...pre[index],
            ...currentMusic
          }
        }else {
          if(!r.resource || r.resource === ''){
            handleVIP();
          }
          pre[index] = {
            ...pre[index],
            ...r
          }
          pre[index].init = true;
        }
        props.setMusicList(_.uniqBy(pre, 'id'));
        props.setCurrentMusic(pre[index]);
      })
    }else if(data.from === 'migu'){
      await getMgPlayMusic(data.id,(r) => {
        let pre = musicList;
        if(r.resource === ''){
          handleVIP();
          flag = false;
          currentMusic.resource = "";
          currentMusic.init = true;
          pre[index] = {
            ...pre[index],
            ...currentMusic
          }
        }else {
          if(!r.resource || r.resource === ''){
            handleVIP();
          }
          pre[index] = {
            ...pre[index],
            ...r
          }
          //console.log(pre[index]);
          pre[index].init = true;
        }
        props.setMusicList(_.uniqBy(pre, 'id'));
        props.setCurrentMusic(pre[index]);
      })
    }
    // this.onSwitchAction();
    // if(flag) {
    //   this.saveLocalStorage();
    // }
  }
  const scrollUp = () => {
    if(showList){
      //console.log('大');
      Animated.timing(scrollAnim, {
        toValue: height*0.6+55,
        duration: 500,
        useNativeDriver:true
      }).start();
      setShowList(false);
    }else {
      //console.log('小');
      // Will change fadeAnim value to 1 in 5 seconds
      Animated.timing(scrollAnim, {
        toValue: 0,
        duration: 500,
        useNativeDriver:true
      }).start();
      setShowList(true);
    }

  };
  function toPlayer(){
    setShowList(false);
    Animated.timing(scrollAnim, {
      toValue: height*0.6+55,
      duration: 10,
      useNativeDriver:true
    }).start();
    navigation.navigate('MusicPlayer')
  }


  return (
    <>
      <View style={styles.toast}>
        <Toast
          ref={toast}
          position="center"
          style={{ backgroundColor: Colors.colorPrimary }}
        />
      </View>
      <View style={
        props.playControlBottom?styles.back:styles.hidden}>
          <View style={props.playControlBottom?styles.absoluteBottom:styles.hidden}>

            <TouchableOpacity onPress={scrollUp}>
              <View style={{marginLeft: 15 }}>
                <AntDesign name={showList?'down':'up'} color={'white'} size={30}></AntDesign>
              </View>
            </TouchableOpacity>

            <TouchableOpacity
              onLayout={(e)=> {
                //console.log('$'+e.nativeEvent.layout.x);
                setImgX(e.nativeEvent.layout.x);
              }}
              onPress={toPlayer}
            >
              <Image
                style={[styles.face,
                  {
                    transform: [
                      {
                        translateX: moveIX,
                      },
                    ],
                  }
                ]}
                source={{uri:props.currentMusic.img}}
              />
            </TouchableOpacity>
            <TouchableOpacity onPress={toPlayer} onLayout={(e)=> {
              setTextX(e.nativeEvent.layout.x);
              setTextWidth(e.nativeEvent.layout.width);
            }}
              style={{
                transform: [
                  {
                    translateX: moveTX,
                  },
                ],
              }}

            >
              <View style={{alignItems: 'center' }} >
                <Text style={styles.playerTextTitle}>{props.currentMusic.title || props.currentMusic.name}</Text>
                <Text style={styles.playerTextYear}>{props.currentMusic.info || props.currentMusic.singer}</Text>

              </View>
            </TouchableOpacity>

            <TouchableOpacity onPress={()=> {
              props.setPlay(!props.play);
            }}>
              <View style={{marginRight: 15 }}>
                {props.play?
                  <AntDesign
                    style={styles.playArrow}
                    name={'pausecircleo'}
                    size={30}
                  />
                :
                  <AntDesign
                    style={styles.playArrow}
                    name={'playcircleo'}
                    size={30}
                  />
                }

              </View>
            </TouchableOpacity>
          </View>

          <Animated.View
            style={[
              styles.scrollUpList,
              {

                transform: [
                  {
                    translateY: scrollAnim,
                  },
                ],


              }
            ]}
          >
            <TouchableOpacity style={styles.foldIco} onPress={() => {
              navigation.navigate('LocalList')
              scrollUp();
            }}>
            <Text style={{position:'relative',left:40,top:20,fontSize:14} }>我的歌单</Text>
            <AntDesign name={'folder1'} style={{position:'relative',left:15,bottom:3} }  size={25} color={'grey'}/>
            </TouchableOpacity>

              <TouchableOpacity style={styles.delIco} onPress={() => props.setMusicList([])}>
              <Text style={{position:'relative',right:40,top:20,fontSize:14} }>删除全部</Text>
              <AntDesign name={'delete'} style={{position:'relative',left:20,bottom:3} } size={25} color={'grey'}/>
              </TouchableOpacity>

            <SongList play={props.setCurrentMusic} add={f} del={props.delMusicList} navigation={navigation} songs={musicList} own={true}/>

          </Animated.View>


        {renderAddPlayList()}
      </View>
    </>
  )
function f(){

}
}
const {height, width} = Dimensions.get('window');
const styles = StyleSheet.create({
  absoluteBottom: {
    zIndex:900,
    position: 'absolute',
    width:width,
    height:55,
    bottom: 0,
    backgroundColor:'#222222',
    flexDirection:'row',
    justifyContent: 'space-between',
    alignItems: 'center'

  },
  hidden: {
    width: 0,
    height: 0,
  },
  playerTextTitle: {
    fontFamily:'Raleway-Bold',
    fontSize: 13,
    fontWeight: 'bold',
    color: '#fff'
  },
  playerTextYear: {
    fontFamily:'Raleway-Regular',
    fontSize: 13,
    fontWeight: '100',
    color: '#fff'
  },
  playArrow: {
    color:'white',
    width:30,
    height:30,
  },
  upArrow: {

    width:30,
    height:30,
  },
  face: {
    width:50,
    height:50,
  },
  scrollUpList:{
    width:width-20,
    zIndex:850,
    position: 'relative',
    top:-55,
    right:-10,
    height: height*0.6, // Bind opacity to animated value
    backgroundColor:'rgb(255,255,255)',
    //padding: 10,
    borderTopLeftRadius:30,
    borderTopRightRadius:30,
    shadowColor: 'grey', // 添加阴影效果
    shadowOffset: {width: 1, height: 1},
    shadowOpacity: 0.5,
    shadowRadius: 2,
    elevation: 2,  // android端要加上这个属性，不然阴影不出来
    padding:15,
    paddingTop:45
  },
  back:{
    position:'absolute',
    bottom:0
  },
  delIco:{
    position:'absolute',
    top:3,
    right:10,

  },
  foldIco:{
    position:'absolute',
    top:3,
    left:10,
  },
  addContain:{
    width:width*0.9,
    height:height*0.6,
    borderWidth:2,
    position:"absolute",
    top:height * -0.2,
    left:width * 0.05,
    justifyContent: 'center', // 子元素沿主轴的对齐方式
    alignItems: 'center',
    zIndex:99999,
    backgroundColor:'rgba(136,135,135,0.43)'
  },
  addInput:{
    borderBottomWidth:2,
    width:width * 0.7,
    fontSize:20,
    marginTop:5,
    paddingLeft:10,
    color:'white'
  },
  addBtn:{
    width:width*0.7,
    height:45,
    borderWidth:2,
    marginTop:10,
    marginBottom:10,
    flexDirection: 'row',
    justifyContent: 'center', // 子元素沿主轴的对齐方式
    alignItems: 'center',
    // backgroundColor:'rgba(100,101,101,0.49)',
    backgroundColor:Colors.colorPrimary,
  },
  toast:{
    position:"absolute",

    height:height,
    width:width
  }
});
